package a08_回溯算法;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * a08_组合总和2复习0
 * </p>
 *
 * @author flyduck
 * @since 2025/1/15
 */
public class a08_组合总和2复习0 {
    //[1,2,1] 3
    public static void main(String[] args) {
        List<List<Integer>> lists = combinationSum2(new int[]{2,5,2,1,2}, 5);
        System.out.println(lists);
    }
    public static List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> result = new ArrayList<>();
        LinkedList<Integer> path = new LinkedList<>();
        boolean[] used = new boolean[candidates.length];
        traversal(result, path, candidates, used,target,0,0);
        return result;
    }

    private static void traversal(List<List<Integer>> result,
                           LinkedList<Integer> path,
                           int[] nums,
                           boolean[] used,
                           int targetSum,
                           int sum,
                           int startIdx){
        if(sum > targetSum){
            return;
        }else if(sum == targetSum){
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = startIdx; i < nums.length; i++) {
            if(i > 0 && nums[i] == nums[i-1] && !used[i- 1]){
                continue;
            }
            sum = sum + nums[i];
            path.add(nums[i]);
            used[i] = true;
            traversal(result, path, nums, used, targetSum, sum, i + 1);
            path.removeLast();
            sum = sum - nums[i];
            used[i] = false;
        }
    }
}
